import { Menu, type MenuProps } from 'antd'
import { CarFilled } from '@ant-design/icons'
import * as Icons from '@ant-design/icons'
import styles from './index.module.less'
import { useStore } from '../../store';
import { useLocation, useNavigate, useRouteLoaderData } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import type { Menu as IMenu } from '../../types/api';
import { findParentKey } from '../../utils';

const SideMenu = () => {
    const data: any = useRouteLoaderData('layout')
    const navigate = useNavigate()
    const { pathname } = useLocation()
    const [selectedKeys, setSelectKeys] = useState<string[]>([])
    const [menuList, setMenuList] = useState<MenuItem[]>([])
    const [stateOpenKeys, setStateOpenKeys] = useState<string[]>([])

    const collapsed = useStore(state => state.collapsed)
    type MenuItem = Required<MenuProps>['items'][number];
    function getItem(
        label: React.ReactNode,
        key?: React.Key | null,
        icon?: React.ReactNode,
        children?: MenuItem[],
    ): MenuItem {
        return {
            label,
            key,
            icon,
            children,
        } as MenuItem;
    }
    function createIcon(name?: string) {
        if (!name) return <></>
        const customer: { [key: string]: any } = Icons
        const icon = customer[name]
        if (!icon) return <></>
        return React.createElement(icon)
    }

    const getTreeMenu = (menuList: IMenu.menuItem[], treeList: MenuItem[] = []) => {
        menuList.forEach((item, index) => {
            if (item.menuType === 1 && item.menuState === 1) {
                if (item.children && !item.buttons) {
                    return treeList.push(getItem(item.menuName, item.path || index, createIcon(item.icon), getTreeMenu(item.children || [])))
                }
                treeList.push(getItem(item.menuName, item.path || index, createIcon(item.icon)))
            }
        })
        return treeList
    }

    useEffect(() => {
        const treeMenuList = getTreeMenu(data.menuList)
        setMenuList(treeMenuList)
        setSelectKeys([pathname])

        // 只在非折叠状态下设置初始打开的菜单项
        if (!collapsed) {
            const initOpenKey = findParentKey(treeMenuList, pathname)
            if (initOpenKey) {
                setStateOpenKeys([String(initOpenKey)])
            }
        }
    }, [data.menuList, pathname])

    // 处理折叠状态变化
    useEffect(() => {
        if (collapsed) {
            // 折叠时清空打开的菜单项
            setStateOpenKeys([])
        } else if (menuList.length > 0) {
            // 展开时恢复当前路径对应的父级菜单项
            const initOpenKey = findParentKey(menuList, pathname)
            if (initOpenKey) {
                setStateOpenKeys([String(initOpenKey)])
            }
        }
    }, [collapsed, menuList, pathname])

    const handleClickMenu = ({ key }: { key: string }) => {
        setSelectKeys([key])
        navigate(key)
    }

    const onOpenChange = (keys: string[]) => {
        setStateOpenKeys(keys)
    }


    return (
        <>
            <div className={styles.logo}>
                <CarFilled />
                <span className={styles.text}>{collapsed ? '' : '莫莫货运'}</span>
            </div>
            <Menu
                mode="inline"
                theme="dark"
                items={menuList}
                style={{
                    width: collapsed ? 80 : 'auto'
                }}
                selectedKeys={selectedKeys}
                onClick={handleClickMenu}
                openKeys={collapsed ? [] : stateOpenKeys}
                onOpenChange={onOpenChange}
            />
        </>
    )
}

export default SideMenu